<?php

define ('PICTURE_FONT', APPLICATION_PATH . '/../public/fonts/verdanab.ttf');
#define ('BUTTON_FONT', APPLICATION_PATH . '/../public/fonts/LucidaGrande.ttf');
define ('BUTTON_FONT', APPLICATION_PATH . '/../public/fonts/verdana.ttf');
define ('BROKEN_IMAGE_ICON', APPLICATION_PATH . '/../public/images/sadface.jpg');
define ('ARC_IMAGE_ICON', APPLICATION_PATH . '/../public/images/prog2.png');
define ('ARC_SWIRL_ICON', APPLICATION_PATH . '/../public/images/swirl.gif');
define ('ARC_SWIRL_ICON_BIG', APPLICATION_PATH . '/../public/images/swirl.80.gif');
#define ('BROKEN_IMAGE_ICON', APPLICATION_PATH . '/../public/images/Missing_Button_icon.png');
define ('PICTURE_SIZE', 240);

function ratio($im, $fill=NULL, $ov=NULL)
{
	$w=imagesx($im);$h=imagesy($im);$r=$w/$h;$d=PICTURE_SIZE;
	if($ov) $d=$ov;
	$condition=$fill?$w<$h:$w>$h;
	return $condition 
	       ? array('x'=>$d,'y'=>$d / $r, 'w'=>$w, 'h'=>$h)
		   : array('y'=>$d,'x'=>$d * $r, 'w'=>$w, 'h'=>$h);
}


class Default_Model_Picture
{

    function Button ($pictureName, $buttonText="", $disabled=NULL) 
    {
        $PICTURE_URI = APPLICATION_PATH . "/../public/images/{$pictureName}";
        $caption    = $buttonText;  
        $width      = 120;
        $picture    = NULL;
        $font_size  = 8;
        $box        = imagettfbbox($font_size, 0, BUTTON_FONT, $caption);
        $fwidth     = $box[2]-$box[0];
        $fheight    = $box[1]-$box[7]; 
        
        $sz         = array('w'=>$fwidth + 8, 'h'=>$fheight + 8, 'x'=>4, 'y'=>11);

        if (file_exists($PICTURE_URI))
        {
            $picture = $this->ImageCreate($PICTURE_URI);
            $sz['w'] += imagesx ($picture) + 2;
            $sz['h']  = max($sz['h'], imagesy($picture) + 8);
            $sz['x'] += imagesx ($picture) + 2; 
        }
        
        $sz ['y']   = 4 + ($sz['h'] / 2); 
        $button     = $this->CreateButton ($sz['w']);# imagecreatetruecolor ($sz['w'], $sz['h']); 
        $white      = imagecolorallocate($button, 0xe9, 0xe8, 0xe8);
        $gray       = imagecolorallocate($button, 125,125,125);
        $fill       = imagecolorallocate($button, 0x8F, 0xBD, 0xDB);
        $red        = imagecolorallocate($button, 0xff, 0xff, 0xff);
        $off        = 2;

     #   imagefill ($button, $off,$off, $white);
     #   imagefilledrectangle ($button, $off,$off,$sz['w'] - $off, $sz['h'] - $off,$fill);
        if ($picture)
        {
            imagecopy($button, $picture, 4, 4, 0, 0, imagesx ($picture), imagesy ($picture));
            imagedestroy ($picture);
        }
        if ($disabled)
            imagettftext($button,  $font_size, 0, $sz['x']+1, $sz['y']+1, $white , BUTTON_FONT, $caption); 
        imagettftext($button,  $font_size, 0, $sz['x'], $sz['y'], $red , BUTTON_FONT, $caption); 

     #   imageline ($button, $off, $sz['h'] - $off, $sz['w'] - $off, $sz['h'] - $off, $gray);
     #   imageline ($button, $sz['w'] - $off, $off, $sz['w'] - $off, $sz['h'] - $off, $gray);
        header("Content-Type: image/png"); 
        imagepng ($button);
        imagedestroy ($button);
    }
    

    function CreateButton ($width) 
    {
        $PICTURE_URI = APPLICATION_PATH . "/../public/images/i.png";
        $raw = $this->ImageCreate ($PICTURE_URI);
        $w=imagesx($raw);
        $h=imagesy($raw);

      
        $f=floor($w/4);
        $im = imagecreatetruecolor ($width, $h);

                    $white = imagecolorallocate ($im, 0xf5, 0xf5, 0xf5);
                    imagefill ($im, 0, 0, $white); 
        
        imagecopyresized($im, $raw, 0, 0, 0, 0, $w, $h, $w,$h);
        imagecopyresized($im, $raw, $width-$f, 0, $w-$f, 0, $w, $h, $w,$h);

        for ($i=0;$i<$h;$i++) {
            $hue = imagecolorat ($raw, $f-1, $i);
            
            $r = ($hue >> 16) & 0xFF;
            $g = ($hue >> 8) & 0xFF;
            $b = $hue & 0xFF;
            $color = imagecolorallocate ($im, $r, $g, $b);
            imageline ($im, $f, $i, $width-$f, $i, $color);
        }

        
        imagedestroy ($raw);
        return $im;

    }
    

    function iButton ($pictureName, $buttonName, $buttonText="", $disabled=NULL) 
    {
        $im = $this->CreateButton (100);

        header("Content-Type: image/png"); 
        imagepng ($im);
        imagedestroy ($im); 
    }
    

    function Arc ($coords, $size=NULL) 
    { 
        $temp    = explode(',', $coords); 
        $percent = is_numeric($temp[1]) && $temp[1] > $temp[0] ? ($temp[0] / $temp[1]) : .01;
        
        if ($percent < .015) {
            header("Content-Type: image/gif"); 
            echo file_get_contents($size && $size > 50 ? ARC_SWIRL_ICON_BIG : ARC_SWIRL_ICON);
            return;
        }

        $circ = strlen($size) > 0 ? $size : 32;
        $size = $circ - 4;

        $half = $circ/2;
        $cover = $this->ImageCreate (ARC_IMAGE_ICON);
        $im = imagecreatetruecolor ($circ,$circ);
        $fill   = imagecolorallocate($im,0x8F,0xBC,0xDB);
        $white  = imagecolorallocate($im, 0xe9, 0xe8, 0xe8);
        $black  = imagecolorallocate($im, 0,0,0);
        # imageantialias($im, true);
        $x = floor(360 * $percent) - 90;
        imagefill ($im, 0, 0, $white);
        imagefilledarc ( $im, $half,$half , $size,$size , -90 , $x , $fill , IMG_ARC_PIE); 
        imagecopyresampled($im, $cover,  0, 0, 0, 0,  $circ,$circ,86,86); 
        header("Content-Type: image/png"); 
        imagepng ($im);
        imagedestroy ($im);
        
    }
    

    function Progress ($coords) 
    {
        $temp    = explode(',', $coords);
        $percent = $temp[0] / $temp[1];
        $im = imagecreate (120, 10);
        $fill   = imagecolorallocate($im,255,0,0);
        $white      = imagecolorallocate($im, 0xe9, 0xe8, 0xe8);
        $x = floor(120 * $percent);
        imagefill ($im, 0, 0, $fill);
        imagefilledrectangle  ($im, $x,0, 120,10, $white);
        header("Content-Type: image/png"); 
        imagepng ($im);
        imagedestroy ($im);
        
    }
    

    function Button_Old ($pictureName) 
    {
        $PICTURE_URI = APPLICATION_PATH . "/../public/images/{$pictureName}";
        $im = $this->ImageCreate ($PICTURE_URI);
        if ($im)
        { 
            header("Content-Type: image/png");  
            imagepng ($im);
            imagedestroy ($im); 
            return;
        } 
        $im = imagecreate (16,16);  
        imagepng ($im);
        imagedestroy ($im); 
    }

    function Slide ($groupName, $Left, $Right)
    {     

         $dir  =  $this->GetGroupFolder ($groupName) . "/thumb";
        if (!is_dir($dir)) mkdir($dir);
        $old = "{$dir}/{$Left}.{$Right}";
        if (file_exists($old)) {
       #     echo file_get_contents ($old);
       #     return;
        }

        $left  = $this->GetPictureById ($groupName, $Left);
        $right = $this->GetPictureById ($groupName, $Right);
        $w = 768;

          $sl = ratio ($left, imagesy($left)>imagesx($left), $w);
          $sr = ratio ($right,imagesy($right)>imagesx($right), $w); 
        $im = imagecreatetruecolor ($w * 2, $w  * .75);

        imagecopyresampled($im, $left,  0, 0, 0, 0,  $sl['x'], $sl['y'], $sl['w'], $sl['h']); 
        imagecopyresampled($im, $right,  $w, 0, 0, 0, $sr['x'], $sr['y'], $sr['w'], $sr['h']); 
        if ($im) 
           header("Content-Type: image/jpeg");  
        imagejpeg ($im, $old, 100);
        imagejpeg ($im, "", 35);
        imagedestroy ($im); 
        imagedestroy ($left); 
        imagedestroy ($right); 
    }

    function GetPictureById ($groupName, $ID)
    {
        $key  = explode ('-', $ID);
        $key  = $key[0];
        $lib  = new Default_Model_MediaIndex(true); 
        $lib->GetArticle($groupName, $ID); 
        $test = $lib->Article; 
        $path = $test
              ? $test['imageuri']
              : $this->GetPicturePath ($groupName, $ID); 
        $im= $this->ImageCreate ($path);   
        if ($im) return $im;  
        $cuz = file_exists($path) ? ' it is an invalid image' : 'it does not exist';
        echo "Could not create image from {$path} using {$groupName}, {$ID} because {$cuz}<br/>";
        exit;
    }

    function GetGroupFolder ($groupName)
    {     
        $assetFolder = DATA_PATH . "/asset";
        return "{$assetFolder}/{$groupName}";
    }

    function GetPicturePath ($groupName, $ID)
    {     
        $base64Name       = base64_encode ($ID); 
        $groupFolder      = $this->GetGroupFolder($groupName); 
        return "{$groupFolder}/{$base64Name}";  
    }

    function Thumbnail ($picturePath=NULL, $Size=NULL, $Square=NULL)
    {     

        if ($picturePath) { 

            $temp  = explode ('/', $picturePath);
            $name  = array_pop($temp);
            $dir   = implode ('/', $temp) . "/thumb";
#
            if (!is_dir($dir)) mkdir ($dir);

            if (!is_dir($dir)) {

echo $dir;
exit;

            }
            $cache = "{$dir}/{$name}";

            if (is_numeric($Size) && $Size > 0) { 
                $dir   = "{$dir}/{$Size}";
                $cache = "{$dir}/{$name}";
                if (!is_dir($dir)) mkdir ($dir);
            }
 
            if (file_exists($cache)) {		
                $im = $this->ImageCreate($cache);
                header("Content-Type: image/jpeg");  
                imagejpeg ($im, "", 100);
                imagedestroy ($im);
                return;
	    }

            $im = $this->ImageCreate ($picturePath);
 
            if ($im)
            { 
                $sz   = ratio ($im);  
                $im_y = $sz['y'];
                if (is_numeric($Size) && $Size > 0) {
                    $sz = $Square=='rect'
                        ? ratio ($im, $Size, $Size)
                        : ratio ($im, 1, $Size)
                        ;
                    $im_y = $Square=='rect' ? ( $sz['x'] * .85 )/* $sz['x']*/ : $sz['y']; 
                }
            
                if (is_numeric($Size) && $Size < 0) $dest = $im;
                else {
                    $dest  = imagecreatetruecolor ($sz['x'], $im_y);
                    $white = imagecolorallocate ($dest, 0xf5, 0xf5, 0xf5);
                    imagefill ($dest, 0, 0, $white); 
                    imagecopyresampled($dest,$im,  0, 0, 0, 0, $sz['x'], $sz['y'], $sz['w'], $sz['h']); 
                } 
          #      header("Content-Type: image/jpeg");  
                imagejpeg ($dest, "", 100);
                if (is_numeric($Size) && $Size > 0) imagejpeg ($dest, $cache, 100);
                imagedestroy ($im);
                imagedestroy ($dest);
                return;
            } 
        }

        $width = is_numeric($Size) ? $Size : PICTURE_SIZE;
            $im = imagecreatetruecolor ($width,$width); 
            $white = imagecolorallocate ($im, 255, 255, 255);
            $black = imagecolorallocate ($im, 0,0,0);
            $broke = $this->ImageCreate(BROKEN_IMAGE_ICON);
            $size  = 96;
            $sz = array ('w' => imagesx($broke),
                          'h' => imagesy($broke),
                          'x' => ($width - $size) / 2,
                          'y' => ($width - $size) / 2
                          );


            imagefill ($im, 0, 0, $white); 
            imagecopyresized($im,$broke,  $sz['x'],  $sz['y'], 0, 0, $size, $size, $sz['w'],  $sz['h']); 
         #   header("Content-Type: image/jpeg");  
            imagejpeg ($im, "", 100);
            imagedestroy ($im);
            imagedestroy ($broke);

    }

    
    function ImageCreate($filename)
    {
        $im = @imagecreatefromjpeg ($filename);
        if (!$im) $im = @imagecreatefromgif ($filename);
        if (!$im) $im = @imagecreatefrompng ($filename);
        return $im;
    }
}

